package com.sky.blue.xmltool.xstream;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * XstreamUtils 建议配合XStream注解一起使用
 * https://blog.csdn.net/qq_21383435/article/details/82116706
 *
 * 最基本的注解@XStreamAlias用于设置字段别名
 * @XStreamAlias("carInfos")
 *
 * 设置xml元素的属性
 * @XStreamAsAttribute
 *
 * List构成的元素集合 carInfo为java集合名 ,用于生成复杂xml
 * @XStreamImplicit(itemFieldName = "carInfo")
 */
public class XstreamUtils {
    /**
     * XML转对象
     *
     * @param clazz 对象类
     * @param xml   字符串
     * @param <T>   T
     * @return
     */
    public static <T> T parseFromXml(Class<T> clazz, String xml) {
        //创建解析XML对象
        XStream xStream = new XStream(new DomDriver());
        //处理注解,声明XStream注解来源
        xStream.processAnnotations(clazz);
        //将XML字符串转为bean对象
        @SuppressWarnings("unchecked")
        T t = (T) xStream.fromXML(xml);
        return t;
    }

    /**
     * 对象转xml
     *
     * @param obj 对象
     * @return
     */
    public static String toXml(Object obj) {
        XStream xStream = new XStream(new DomDriver());
        //声明XStream注解来源
        xStream.processAnnotations(obj.getClass());
        return xStream.toXML(obj);
    }
}
